package classfile

import "fmt"

type ConstantPool []ConstantInfo

func readConstantPoolCount(reader *ClassReader) uint16 {
	constantPoolCount := reader.readUint16()
	return constantPoolCount
}

func readConstantPool(reader *ClassReader, count uint16) ConstantPool {
	cpCount := int(count)
	//fmt.Printf("the numbers of constant in constantPool: %d\n", cpCount)
	// 创建切片，存放常量对象
	cp := make([]ConstantInfo, cpCount)
	for i := 1; i < cpCount; i++ {
		//fmt.Printf("the cp[%d] is %v\n", i, cp[i])
		cp[i] = readConstantInfo(reader, cp)
		switch cp[i].(type) {
		case *ConstantLongInfo, *ConstantDoubleInfo:
			i++
		}
	}
	return cp
}

// 获取常量
func (self ConstantPool) getConstantInfo(index uint16) ConstantInfo {
	//fmt.Println(self[index]) self[index] nil
	if cpInfo := self[index]; cpInfo != nil {
		return cpInfo
	}
	//fmt.Println(self[index])
	panic(fmt.Errorf("Invalid constant pool index: %v!", index))
}

func (self ConstantPool) getNameAndType(index uint16) (string, string) {
	ntInfo := self.getConstantInfo(index).(*ConstantNameAndTypeInfo)
	name := self.getUtf8(ntInfo.nameIndex)
	_type := self.getUtf8(ntInfo.descriptorIndex)
	return name, _type
}

func (self ConstantPool) getClassName(index uint16) string {
	classInfo := self.getConstantInfo(index).(*ConstantClassInfo)
	return self.getUtf8(classInfo.nameIndex)
}

// 获取UTF8常量的string
func (self ConstantPool) getUtf8(index uint16) string {
	// 断言，将self.getConstantInfo(index)转化为(*ConstantUtf8Info)指针指向的结构体类型
	utf8Info := self.getConstantInfo(index).(*ConstantUtf8Info)
	return utf8Info.str
}
